package artid.com.arttogoa;

import java.io.File;
import org.apache.commons.lang3.StringUtils;
import org.xutils.x;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.ConsultationInfo;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.VioceUtils;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称   ：ReleaseConsultationActivity   
 * 类描述   ：发布咨询
 * 创建人   ：耿卫斌   
 * 创建时间：2016-8-1 下午3:02:02   
 *
 */
public class ReleaseConsultationActivity extends BaseActivity implements
OnClickListener {
	private TextView mRelease;
	private EditText name, content;
	private ImageView releasephoto, showPhoto;
	String path, baseImage;;
	Uri imgUri;
	Boolean isSetPic = false;
	RelativeLayout addimg;
	String description = "";
	View mViewCatelogy;
	AlertDialog alertDialog;
	String strCateId = "0";
	TextView textConCate;
	private ImageLoader mImageLoader;
	ImageView imgVoice;
	private String PhotoPath;//剪裁之后的图片路径
	private Bitmap clipBitmap;//剪裁之后的图片
	private String Bitmap64;//剪裁之后的图片流

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_release_consultation);
		initView();
		Bundle bundle = getIntent().getExtras();
		if (bundle!=null) {
			ConsultationInfo item =  (ConsultationInfo) getIntent().getExtras().getSerializable("item");
			if (!TextUtils.isEmpty(item.getTitle())) {
				name.setText(item.getTitle());
				mTittle.setText(item.getTitle());
			}
			if (!TextUtils.isEmpty(item.getDescription())) {
				content.setText(item.getDescription());
			}
			if (!TextUtils.isEmpty(item.getType())) {
				try {
					setType(Integer.valueOf(item.getType()));
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			if (!TextUtils.isEmpty(item.getImgurl())) {
				RequestQueue mQueue = Volley.newRequestQueue(ReleaseConsultationActivity.this);
				mImageLoader = new ImageLoader(mQueue, new BitmapCache());
				ImageListener listener = ImageLoader
						.getImageListener(showPhoto, R.drawable.yspba_img_mor,
								android.R.drawable.ic_delete);
				mImageLoader.get(item.getImgurl(),listener);	
				showPhoto.setVisibility(View.VISIBLE);
			}

		}
	}

	private void initView() {
		mContext = this;
		imgVoice = (ImageView)findViewById(R.id.iv_vioce);
		imgVoice.setOnClickListener(this);
		path = Environment.getExternalStorageDirectory() + "/pintu" + "ti.jpg";
		File file = new File(path);
		if (file.exists())
			file.delete();
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("发布资讯");
		setBack();
		mReleaseIcon = (ImageView) findViewById(R.id.release_icon);
		mReleaseIcon.setVisibility(View.VISIBLE);
		mReleaseIcon.setOnClickListener(this);
		mRelease = (TextView) findViewById(R.id.release_btn);
		mRelease.setOnClickListener(this);
		name = (EditText) findViewById(R.id.dynamic_release_name);
		content = (EditText) findViewById(R.id.dynamic_release_content);
		releasephoto = (ImageView) findViewById(R.id.add_img);
		releasephoto.setOnClickListener(this);
		addimg = (RelativeLayout) findViewById(R.id.add_img_layout);
		addimg.setOnClickListener(this);
		showPhoto = (ImageView) findViewById(R.id.image_showpic);
		mViewCatelogy = (View) findViewById(R.id.view_consu_cate);
		mViewCatelogy.setOnClickListener(this);
		textConCate = (TextView)findViewById(R.id.textView1);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_vioce:
			VioceUtils vu = new VioceUtils(ReleaseConsultationActivity.this, imgVoice, content);
			vu.init();
			break;
		case R.id.release_icon:
			alertDialog = AlertUtils.showConsultaDialog(
					ReleaseConsultationActivity.this,
					ReleaseConsultationActivity.this.getWindowManager()
					.getDefaultDisplay().getWidth(),
					new OnClickListener() {
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							switch (view.getId()) {
							case R.id.imageView2:
								alertDialog.dismiss();
								break;
							default:
								break;
							}
						}
					});
			break;
		case R.id.release_btn:
			submit();
			break;
		case R.id.add_img_layout:
			showPopupWindow();
			break;
		case R.id.add_img:
			showPopupWindow();
			break;
		case R.id.view_consu_cate:
			alertDialog = AlertUtils.initCateAlertDialog(
					ReleaseConsultationActivity.this,
					ReleaseConsultationActivity.this.getWindowManager()
					.getDefaultDisplay().getWidth(),
					new OnClickListener() {
						@Override
						public void onClick(View view) {
							// TODO Auto-generated method stub
							switch (view.getId()) {
							case R.id.tv_yspzx:
								setType(1);
								alertDialog.dismiss();
								break;
							case R.id.tv_pmzx:
								setType(2);
								alertDialog.dismiss();
								break;
							case R.id.tv_hlzx:
								setType(4);
								alertDialog.dismiss();
								break;
							case R.id.tv_zhzx:
								setType(3);
								alertDialog.dismiss();
								break;
							default:
								break;
							}
						}
					});
			break;
		default:
			break;
		}

	}

	void setType(int type){
		switch (type) {
		case 1:
			strCateId = "1";
			textConCate.setText("艺术品资讯");

			break;
		case 2:
			strCateId = "2";
			textConCate.setText("拍卖动态");

			break;
		case 4:
			textConCate.setText("画廊资讯");
			strCateId = "4";

			break;
		case 3:
			textConCate.setText("展会资讯");
			strCateId = "3";

			break;
		default:
			break;
		}
	}
	// 点击头像，选择照片
	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext,Integer.parseInt(NetUtils.getDisplayMetrics(ReleaseConsultationActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_phone:
					//检查权限
					if (ContextCompat.checkSelfPermission(ReleaseConsultationActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					//照相机	
					CameraUtils.openCameraImage(ReleaseConsultationActivity.this);
					AlertUtils.dismiss();
					break;
				case R.id.tv_choice:
					//从相册获取
					CameraUtils.openLocalImage(ReleaseConsultationActivity.this);
					AlertUtils.dismiss();
					break;
				default:
					break;
				}
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri=CameraUtils.imageUriFromCamera;
			if(uri != null) {
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath",  BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}else{
				//防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(uri != null) {
							Intent i=new Intent(mContext,Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			//判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if(requestCode==200){
			//获取剪切后的图片路径
			if(data!=null){
				PhotoPath=data.getExtras().getString("PhotoPath");  
				if(!StringUtils.isEmpty(PhotoPath)){
					clipBitmap=BitmapUtil.getSmallBitmap(PhotoPath, 500, 500);
					//设置图片
					showPhoto.setImageBitmap(clipBitmap);
					showPhoto.setVisibility(View.VISIBLE);
					Bitmap64= BitmapUtil.bitmaptoString(clipBitmap);

				}
			}
		}
	}

	private void submit() {
		VolleyBasic.showLoding(mContext);
		if(showPhoto.getVisibility()!=View.VISIBLE){
			Toast.makeText(mContext, "请选择资讯图片", 2).show();
			return;
		}
		if (strCateId.equals("0")) {
			Toast.makeText(mContext, "请选择资讯类别", 2).show();
			return;
		}
		if (TextUtils.isEmpty(name.getText().toString())) {
			Toast.makeText(mContext, "请输入动态名称~", 2).show();
			return;
		} else if (TextUtils.isEmpty(content.getText().toString())) {
			Toast.makeText(mContext, "请输入作品描述~", 2).show();
			return;
		}
		RequestParams params=new RequestParams(Cache.consultationRelease);
		params.addHeader("Accept",  "application/json, text/javascript, */*");
		params.addParameter("token", AppUtil.getUser().getToken());
		params.addParameter("title", name.getText().toString());
		params.addParameter("imgdata", Bitmap64);
		params.addParameter("description", content.getText().toString());
		params.addParameter("category_id", strCateId);
		x.http().post(params, new CommonCallback<String>() {

			@Override
			public void onCancelled(CancelledException cex) {
				// TODO Auto-generated method stub
				System.out.println("主动停止网络请求");
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				// TODO Auto-generated method stub
				//请求错误
				if(isOnCallback==false){
					//ex异常信息不是来自回调方法
					System.out.println("ex异常信息不是来自回调方法："+ex.getMessage());
				}else{
					//ex异常信息是来自回调方法
					System.out.println("ex异常信息是来自回调方法："+ex.getMessage());
				}
				VolleyBasic.disMissLoding();
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				System.out.println("请求完毕,不管成功失败");
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				//成功
				Log.d("log", "Post请求结果："+result);
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(!StringUtils.isEmpty(PhotoPath)){
							BitmapUtil.deleteBitmap(PhotoPath);
						}
						showToast("发布成功");
						Intent intent1 = new Intent("com.ArtConsultationActivity.receiver");  
						intent1.putExtra("isRefresh", true);
						sendBroadcast(intent1);
						VolleyBasic.disMissLoding();
						finish();
					}
				}, 2000);
			}
		});
	}

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}


}
